package com.cr.sync.service.impl;

import com.cr.common.utils.uuid.IdUtils;
import com.cr.sync.domain.TbSyncSuperviseCheckTask;
import com.cr.sync.domain.TbSyncSuperviseCheckTaskDetail;
import com.cr.sync.mapper.TbSyncSuperviseCheckTaskDetailMapper;
import com.cr.sync.mapper.TbSyncSuperviseCheckTaskMapper;
import com.cr.sync.service.ITbSyncSuperviseCheckTaskService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 远程数据-巡查任务Service业务层处理
 * 
 * @author tang
 * @date 2025-08-29
 */
@Service
public class TbSyncSuperviseCheckTaskServiceImpl implements ITbSyncSuperviseCheckTaskService 
{

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void insertBatch(List<TbSyncSuperviseCheckTask> data) {
        if(data != null && !data.isEmpty()) {

            SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            TbSyncSuperviseCheckTaskMapper mapper = sqlSession.getMapper(TbSyncSuperviseCheckTaskMapper.class);
            TbSyncSuperviseCheckTaskDetailMapper detailMapper = sqlSession.getMapper(TbSyncSuperviseCheckTaskDetailMapper.class);

            try {
                // 先删除旧数据
                mapper.deleteAll();
                detailMapper.deleteAll();

                // 添加新数据
                for(int i = 0; i < data.size(); i ++) {
                    TbSyncSuperviseCheckTask tbSyncSuperviseCheckTask = data.get(i);
                    String taskId = IdUtils.simpleUUID();

                    tbSyncSuperviseCheckTask.setId(taskId);
                    mapper.insertTbSyncSuperviseCheckTask(tbSyncSuperviseCheckTask);

                    // 添加巡查明细
                    List<TbSyncSuperviseCheckTaskDetail> checkResultDetail = tbSyncSuperviseCheckTask.getCheckResultDetail();
                    if(checkResultDetail != null && !checkResultDetail.isEmpty()) {
                        for (TbSyncSuperviseCheckTaskDetail detail : checkResultDetail) {
                            detail.setTaskId(taskId);
                            detailMapper.insertTbSyncSuperviseCheckTaskDetail(detail);
                        }
                    }

                    // 每200条提交一次事务
                    if (i > 0 && i % 200 == 0) {
                        sqlSession.flushStatements();
                        sqlSession.clearCache();
                    }
                }

                sqlSession.commit();
            } catch (Exception e) {
                sqlSession.rollback();
                throw new RuntimeException(e);
            } finally {
                sqlSession.close();
            }
        }
    }

}
